<template>
  <div
    :id="`comment-${comment.id}`"
    class="comment-item"
    :class="{ 'is-reply': comment.level > 1, highlighted: isHighlighted }"
  >
    <!-- 评论主体 -->
    <div class="comment-main">
      <!-- 头像 -->
      <div class="comment-avatar">
        <el-avatar
          :size="comment.level === 1 ? 40 : 32"
          :src="formatAvatarUrl(commentAuthor.avatar)"
          :alt="commentAuthor.nickName"
        >
          {{ commentAuthor.nickName?.charAt(0) || "?" }}
        </el-avatar>
      </div>

      <!-- 评论内容区域 -->
      <div class="comment-content">
        <!-- 用户信息和时间 -->
        <div class="comment-meta">
          <span class="author-name">{{ commentAuthor.nickName }}</span>

          <!-- 回复标识 -->
          <span v-if="comment.replyToUser" class="reply-to">
            回复 @{{ comment.replyToUser.nickName }}
          </span>

          <span class="comment-time">{{ formatTime(comment.createTime) }}</span>

          <!-- 敏感词标识 -->
          <el-tag v-if="comment.isSensitive" type="warning" size="small">
            敏感内容
          </el-tag>
        </div>

        <!-- 评论文本 -->
        <div class="comment-text">
          {{ comment.content }}
        </div>

        <!-- 评论图片 -->
        <div v-if="shouldShowImages" class="comment-images">
          <!-- 加载中状态 -->
          <div v-if="imagesLoading" class="images-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载图片中...</span>
          </div>

          <!-- 图片显示 -->
          <CommentImageViewer
            v-else-if="commentImages && commentImages.length > 0"
            :images="commentImages"
            :max-display="9"
          />

          <!-- 没有图片时的提示（仅在已加载且没有图片时显示） -->
          <div
            v-else-if="imagesLoaded && commentImages.length === 0"
            class="no-images"
          >
            <!-- 静默处理，不显示任何内容 -->
          </div>
        </div>

        <!-- 操作栏 -->
        <div class="comment-actions">
          <!-- 点赞按钮 -->
          <div class="action-item like-action">
            <el-button
              text
              :type="comment.isLiked ? 'primary' : 'default'"
              :loading="comment.isLiking"
              size="small"
              @click="toggleLike"
            >
              <el-icon><LinearNewOhterLikeThumbUp /></el-icon>
              <span v-if="comment.likeCount > 0">
                {{ formatNumber(comment.likeCount) }}
              </span>
            </el-button>
          </div>

          <!-- 回复按钮 -->
          <div v-if="canReply" class="action-item reply-action">
            <el-button text size="small" @click="toggleReply">
              <el-icon><ChatDotRound /></el-icon>
              回复
            </el-button>
          </div>

          <!-- 删除按钮（仅作者可见） -->
          <div v-if="canDelete" class="action-item delete-action">
            <el-button text type="danger" size="small" @click="handleDelete">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>

        <!-- 回复编辑器 -->
        <div v-if="showReplyEditor" class="reply-editor">
          <div class="comment-publisher">
            <CommentPublisher
              :article-id="articleId"
              :parent-id="comment.id"
              :reply-to-user-id="commentAuthor.userId"
              :placeholder="`回复 @${commentAuthor.nickName}...`"
              compact
              @publish="handleReplyPublish"
              @cancel="handleReplyCancel"
              @content-change="handleReplyContentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 子评论列表 - 只在顶级评论显示，且不递归 -->
    <div
      v-if="
        comment.level === 1 && comment.children && comment.children.length > 0
      "
      class="comment-children"
    >
      <div
        v-for="child in displayedChildren"
        :key="child.id"
        class="child-comment"
      >
        <CommentItem
          :comment="child"
          :article-id="articleId"
          :max-level="2"
          :children-limit="childrenLimit"
          :flat-replies="true"
          :active-reply-comment-id="activeReplyCommentId"
          @like="handleChildLike"
          @reply="$emit('reply', $event)"
          @delete="$emit('delete', $event)"
          @toggle-reply="$emit('toggleReply', $event)"
          @reply-content-change="$emit('replyContentChange', $event)"
        />
      </div>

      <!-- 展开/收起按钮 -->
      <div v-if="flattenedChildren.length > 2" class="toggle-replies">
        <el-button text size="small" @click="toggleRepliesExpanded">
          <el-icon
            ><ArrowDown v-if="!repliesExpanded" /><ArrowUp v-else
          /></el-icon>
          {{
            repliesExpanded
              ? "收起回复"
              : `查看全部${flattenedChildren.length}条回复`
          }}
        </el-button>
      </div>

      <!-- 加载更多回复按钮 -->
      <!-- <div
        class="load-more-replies"
        v-if="
          comment.hasMoreChildren &&
          comment.childrenTotal > comment.children.length
        "
      >
        <el-button
          text
          @click="$emit('load-more-children', comment.id)"
          size="small"
        >
          查看全部 {{ comment.childrenTotal }} 条回复
        </el-button>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, inject, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  ChatDotRound,
  Delete,
  ArrowDown,
  ArrowUp,
  Loading
} from "@element-plus/icons-vue";
import { LinearNewOhterLikeThumbUp } from "@element-extended-icon-pack/vue";
import type { ArticleCommentResponse } from "@/api/user-comment";
import { UserCommentUtils } from "@/api/user-comment";
import { type CommentImageInfo } from "@/api/comment-image";
import { useUserAuthStore } from "@/store/modules/userAuth";
import { formatAvatarUrl } from "@/utils/avatar";
import CommentPublisher from "./CommentPublisher.vue";
import CommentImageViewer from "./CommentImageViewer.vue";

// Props定义
interface Props {
  /** 评论数据 */
  comment: ArticleCommentResponse;
  /** 文章ID */
  articleId: number;
  /** 最大评论层级 */
  maxLevel?: number;
  /** 每个根评论显示的回复数量 */
  childrenLimit?: number;
  /** 是否扁平化回复 */
  flatReplies?: boolean;
  /** 当前活跃的回复评论ID */
  activeReplyCommentId?: number | null;
  /** 评论图片列表（外部传入） */
  commentImages?: CommentImageInfo[];
  /** 图片加载状态（外部传入） */
  imagesLoading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  maxLevel: 2,
  childrenLimit: 5,
  flatReplies: true,
  activeReplyCommentId: null,
  commentImages: () => [],
  imagesLoading: false
});

// Emits定义
const emit = defineEmits<{
  like: [commentId: number];
  reply: [newReply: ArticleCommentResponse];
  delete: [commentId: number];
  loadMoreChildren: [commentId: number];
  toggleReply: [commentId: number];
  replyContentChange: [data: { commentId: number; hasContent: boolean }];
}>();

// 用户认证store
const userAuthStore = useUserAuthStore();

// 路由实例
const route = useRoute();

// 回复展开状态
const repliesExpanded = ref(false);

// 回复输入框内容状态
const replyHasContent = ref(false);

// 高亮状态
const isHighlighted = ref(false);

// 从父组件注入图片数据获取函数
const injectedGetCommentImages = inject<
  ((commentId: number) => CommentImageInfo[]) | null
>("getCommentImages", null);
const injectedIsImageLoading = inject<((commentId: number) => boolean) | null>(
  "isImageLoading",
  null
);

// 评论图片（优先使用注入的数据，否则使用props）
const commentImages = computed(() => {
  if (injectedGetCommentImages) {
    return injectedGetCommentImages(props.comment.id);
  }
  return props.commentImages || [];
});

const imagesLoading = computed(() => {
  if (injectedIsImageLoading) {
    return injectedIsImageLoading(props.comment.id);
  }
  return props.imagesLoading || false;
});

const imagesLoaded = computed(() => {
  // 如果有注入的数据获取函数，则认为已加载（由父组件管理）
  if (injectedGetCommentImages) {
    return true;
  }
  // 否则根据props判断
  return props.commentImages !== undefined || !props.imagesLoading;
});

// 计算属性
const isLoggedIn = computed(() => userAuthStore.isLoggedIn);
const currentUserId = computed(() => userAuthStore.userId);

// 兼容不同的数据结构：comment.author 或 comment.user
const commentAuthor = computed(() => {
  // 优先使用 author 字段
  if (props.comment.author) {
    return props.comment.author;
  }

  // 兼容使用 user 字段的情况
  if (props.comment.user) {
    return props.comment.user;
  }

  // 如果都没有，返回默认值避免错误
  console.warn("评论数据缺少用户信息:", props.comment);
  return {
    userId: 0,
    nickName: "未知用户",
    avatar: "",
    sex: "0"
  };
});

// 是否可以回复
const canReply = computed(() => {
  return (
    isLoggedIn.value && UserCommentUtils.canReply(props.comment, props.maxLevel)
  );
});

// 是否可以删除（只有作者可以删除自己的评论）
const canDelete = computed(() => {
  return isLoggedIn.value && currentUserId.value === commentAuthor.value.userId;
});

// 是否显示回复编辑器
const showReplyEditor = computed(() => {
  return props.activeReplyCommentId === props.comment.id;
});

// 是否应该显示图片区域
const shouldShowImages = computed(() => {
  return (
    imagesLoading.value ||
    (imagesLoaded.value && commentImages.value.length > 0)
  );
});

// 扁平化子评论 - 将所有层级的子评论展平到第二层级显示
const flattenedChildren = computed(() => {
  if (!props.comment.children || props.comment.children.length === 0) {
    return [];
  }

  const flattenComments = (
    comments: ArticleCommentResponse[]
  ): ArticleCommentResponse[] => {
    const result: ArticleCommentResponse[] = [];

    for (const comment of comments) {
      // 将评论添加到结果中，并设置为第2层级
      const flatComment = {
        ...comment,
        level: 2
      };
      result.push(flatComment);

      // 如果有子评论，递归扁平化并添加到结果中
      if (comment.children && comment.children.length > 0) {
        const childrenFlattened = flattenComments(comment.children);
        result.push(...childrenFlattened);
      }
    }

    return result;
  };

  return flattenComments(props.comment.children);
});

// 显示的子评论 - 根据展开状态决定显示数量
const displayedChildren = computed(() => {
  const children = flattenedChildren.value;

  if (children.length <= 2 || repliesExpanded.value) {
    return children;
  }

  // 只显示2条回复，优先显示点赞量最高的，其次是最早的
  const sortedChildren = [...children].sort((a, b) => {
    // 首先按点赞数排序（降序）
    if (b.likeCount !== a.likeCount) {
      return b.likeCount - a.likeCount;
    }
    // 点赞数相同时按时间排序（升序，最早的在前）
    return new Date(a.createTime).getTime() - new Date(b.createTime).getTime();
  });

  return sortedChildren.slice(0, 2);
});

// 格式化时间
const formatTime = (timeStr: string): string => {
  return UserCommentUtils.formatTime(timeStr);
};

// 格式化数字
const formatNumber = (num: number): string => {
  return UserCommentUtils.formatNumber(num);
};

// 切换点赞状态
const toggleLike = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning("请先登录后再点赞");
    return;
  }

  if (props.comment.isLiking) {
    return; // 防止重复点击
  }

  console.log("👍 CommentItem toggleLike:", {
    commentId: props.comment.id,
    currentLiked: props.comment.isLiked,
    likeCount: props.comment.likeCount
  });

  // 直接触发点赞事件，不传递参数，让父组件处理
  emit("like", props.comment.id);
};

// 处理子评论点赞
const handleChildLike = (commentId: number) => {
  console.log("👶 子评论点赞传递:", {
    commentId
  });
  emit("like", commentId);
};

// 切换回复状态
const toggleReply = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning("请先登录后再回复");
    return;
  }

  emit("toggleReply", props.comment.id);
};

// 处理回复发表
const handleReplyPublish = (newReply: ArticleCommentResponse) => {
  // 关闭回复框
  emit("toggleReply", props.comment.id);
  emit("reply", newReply);
};

// 处理删除
const handleDelete = () => {
  emit("delete", props.comment.id);
};

// 处理回复内容变化
const handleReplyContentChange = (hasContent: boolean) => {
  replyHasContent.value = hasContent;
  emit("replyContentChange", {
    commentId: props.comment.id,
    hasContent
  });
};

// 处理回复取消
const handleReplyCancel = () => {
  // 如果有内容，提示用户确认
  if (replyHasContent.value) {
    ElMessage.warning("输入框中有内容，请先清空内容或发布评论");
    return;
  }

  // 没有内容时正常取消
  replyHasContent.value = false;
  emit("toggleReply", props.comment.id);
};

// 切换回复展开状态
const toggleRepliesExpanded = () => {
  repliesExpanded.value = !repliesExpanded.value;
};

// 图片加载逻辑已移至 CommentTree 组件中进行批量处理

// 检查子评论中是否包含目标 hash
const checkChildrenForHash = (hash: string): boolean => {
  if (!props.comment.children || props.comment.children.length === 0) {
    return false;
  }

  // 递归检查所有子评论
  const checkComments = (comments: ArticleCommentResponse[]): boolean => {
    for (const child of comments) {
      const childId = `comment-${child.id}`;
      if (hash === `#${childId}`) {
        return true;
      }
      if (child.children && child.children.length > 0) {
        if (checkComments(child.children)) {
          return true;
        }
      }
    }
    return false;
  };

  return checkComments(props.comment.children);
};

// 检查并处理 hash 定位高亮
const checkAndHighlight = () => {
  const hash = route.hash;
  if (!hash) return;

  const targetCommentId = `comment-${props.comment.id}`;

  // 检查是否是当前评论
  if (hash === `#${targetCommentId}`) {
    console.log("✨ 当前评论匹配 hash:", props.comment.id);
    // 添加高亮效果
    isHighlighted.value = true;

    // 2秒后移除高亮
    setTimeout(() => {
      isHighlighted.value = false;
    }, 2000);
    return;
  }

  // 检查是否是子评论，如果是则展开回复列表
  if (props.comment.level === 1 && checkChildrenForHash(hash)) {
    console.log("📦 子评论匹配 hash，展开回复列表:", props.comment.id);

    // 如果已经展开，不需要重复操作
    if (repliesExpanded.value) {
      return;
    }

    // 展开回复列表
    repliesExpanded.value = true;

    // 展开后需要稍微延迟，等待 DOM 更新，然后重新触发滚动
    setTimeout(() => {
      const element = document.querySelector(hash);
      if (element) {
        console.log("🎯 展开后重新定位到:", hash);
        element.scrollIntoView({
          behavior: "smooth",
          block: "center"
        });
      }
    }, 300); // 等待展开动画完成
  }
};

// 组件挂载时检查
onMounted(() => {
  // 延迟检查，确保 DOM 已完全渲染
  setTimeout(checkAndHighlight, 100);
});

// 监听路由 hash 变化
watch(
  () => route.hash,
  () => {
    checkAndHighlight();
  }
);
</script>

<style scoped lang="scss">
// 高亮动画关键帧
@keyframes highlight-flash {
  0% {
    background-color: #fff9e6;
    box-shadow: 0 0 0 3px #ffd700;
  }

  50% {
    background-color: #fffbf0;
    box-shadow: 0 0 0 2px #ffeb99;
  }

  100% {
    background-color: transparent;
    box-shadow: 0 0 0 0 transparent;
  }
}

// 暗色主题高亮动画
@keyframes highlight-flash-dark {
  0% {
    background-color: #3a3a2a;
    box-shadow: 0 0 0 3px #b8860b;
  }

  50% {
    background-color: #2a2a2a;
    box-shadow: 0 0 0 2px #9a7506;
  }

  100% {
    background-color: transparent;
    box-shadow: 0 0 0 0 transparent;
  }
}

// 移动端适配
@media (width <= 768px) {
  .comment-item {
    &.is-reply {
      margin-left: 10px;
    }

    .comment-main {
      gap: 8px;

      .comment-content {
        .comment-actions {
          gap: 12px;
        }
      }
    }

    .comment-children {
      margin-left: 32px;

      .child-comment {
        padding-left: 12px;
      }
    }
  }
}

.comment-item {
  padding: 12px;
  scroll-margin-top: 80px; // 为固定头部预留空间
  border-radius: 8px;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: #f8f9fa;
  }

  // 高亮动画效果
  &.highlighted {
    background-color: #fff9e6;
    box-shadow: 0 0 0 3px #ffd700;
    animation: highlight-flash 2s ease;
  }

  &.is-reply {
    margin-left: 20px;

    .comment-main {
      padding: 12px 0;
    }
  }

  .comment-main {
    display: flex;
    gap: 12px;
    padding: 0;

    .comment-avatar {
      flex-shrink: 0;
    }

    .comment-content {
      flex: 1;
      min-width: 0;

      .comment-meta {
        display: flex;
        gap: 10px;
        align-items: center;
        margin-bottom: 8px;
        font-size: 14px;

        .author-name {
          font-size: 15px;
          font-weight: 600;
          color: #1d2129;
        }

        .reply-to {
          font-weight: 500;
          color: #1e80ff;
          text-decoration: none;
          transition: color 0.2s ease;

          &:hover {
            color: #06c;
          }
        }

        .comment-time {
          font-size: 13px;
          color: #8a919f;
        }
      }

      .comment-text {
        margin-bottom: 12px;
        font-size: 15px;
        line-height: 1.6;
        color: #1d2129;
        word-break: break-word;
      }

      .comment-images {
        margin: 8px 0 12px;

        .images-loading {
          display: flex;
          gap: 8px;
          align-items: center;
          padding: 8px 0;
          font-size: 13px;
          color: #8a919f;

          .el-icon {
            font-size: 14px;
          }
        }

        .no-images {
          display: none; // 隐藏空状态
        }
      }

      .comment-actions {
        display: flex;
        gap: 16px;
        align-items: center;

        .action-item {
          .el-button {
            padding: 6px 12px;
            font-size: 13px;
            color: #8a919f;
            background: transparent;
            border: none;
            border-radius: 16px;
            transition: all 0.2s ease;

            .el-icon {
              margin-right: 6px;
              font-size: 16px;
            }

            &:hover {
              color: #1e80ff;
              background-color: #f2f6ff;

              .el-icon {
                transform: scale(1.1);
              }
            }
          }
        }

        .like-action {
          .el-button {
            .el-icon {
              font-size: 16px;
            }
          }

          .el-button.is-text.el-button--primary {
            color: #ff6b6b;
            background-color: #fff5f5;

            &:hover {
              color: #ff5252;
              background-color: #ffebee;
            }
          }
        }
      }

      .reply-editor {
        padding: 12px;
        margin-top: 12px;
        background-color: #f8f9fa;
        border-radius: 8px;

        .comment-publisher {
          background: transparent;
        }
      }
    }
  }

  .comment-children {
    padding: 12px;
    margin-top: 12px;
    margin-left: 40px;
    background: #f8f9fa;
    border-radius: 8px;

    .child-comment {
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .toggle-replies {
      margin-top: 12px;
      text-align: center;

      .el-button {
        padding: 6px 16px;
        font-size: 13px;
        font-weight: 500;
        color: #1e80ff;
        background: #f2f6ff;
        border: none;
        border-radius: 16px;
        transition: all 0.2s ease;

        .el-icon {
          margin-right: 4px;
          font-size: 14px;
          transition: transform 0.2s ease;
        }

        &:hover {
          color: #06c;
          background: #e6f3ff;

          .el-icon {
            transform: scale(1.1);
          }
        }
      }
    }

    .load-more-replies {
      margin-top: 16px;
      text-align: center;

      .el-button {
        padding: 8px 20px;
        font-size: 14px;
        font-weight: 500;
        color: #1e80ff;
        background: #fff;
        border: none;
        border-radius: 20px;
        transition: all 0.2s ease;

        &:hover {
          color: #fff;
          background: #1e80ff;
        }
      }
    }
  }
}

// 暗色主题适配
.dark {
  .comment-item {
    &:hover {
      background-color: #2a2a3a;
    }

    // 暗色主题高亮效果
    &.highlighted {
      background-color: #3a3a2a;
      box-shadow: 0 0 0 3px #b8860b;
      animation: highlight-flash-dark 2s ease;
    }

    .comment-main {
      .comment-content {
        .comment-meta {
          .author-name {
            color: #e5e6eb;
          }

          .comment-time {
            color: #86909c;
          }
        }

        .comment-text {
          color: #e5e6eb;
        }

        .comment-images {
          .images-loading {
            color: #86909c;
          }
        }

        .comment-actions {
          .action-item {
            .el-button {
              color: #86909c;

              &:hover {
                color: #1e80ff;
                background-color: #2a2a3a;
              }
            }
          }
        }

        .reply-editor {
          background-color: #2a2a3a;
        }
      }
    }
  }

  .comment-children {
    background: #2a2a3a;

    .toggle-replies {
      .el-button {
        color: #1e80ff;
        background: #1e2a3a;

        &:hover {
          color: #66b3ff;
          background: #253040;
        }
      }
    }

    .load-more-replies {
      .el-button {
        color: #1e80ff;
        background: #1e1e28;

        &:hover {
          color: #fff;
          background: #1e80ff;
        }
      }
    }
  }
}
</style>
